package com.example.homeworkmanagement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.homeworkmanagement.dto.*;
import com.example.homeworkmanagement.mapper.TeachersMapper;
import com.example.homeworkmanagement.pojo.*;
import com.example.homeworkmanagement.mapper.TeachesMapper;
import com.example.homeworkmanagement.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.homeworkmanagement.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 拒绝加班
 * @since 2025-05-25
 */
@Service
public class TeachesServiceImpl extends ServiceImpl<TeachesMapper, Teaches> implements TeachesService {
    @Autowired
    private TeachesMapper teachesMapper;
    @Autowired
    private TeachersMapper teachersMapper;
    @Autowired
    private ClassesService classesService;
    @Autowired
    private AssignmentsService assignmentsService;
    @Autowired
    private CoursesService coursesService;

    @Override
    public ResultVO<TeachesAndClassesDTO> getTeachesDetail(Integer teachId) {
        try {
            Teaches teaches = this.getOne(new QueryWrapper<Teaches>().eq("teach_id", teachId));
            if (teaches == null) {
                return ResultVO.fail("教学安排id不存在");
            }
            TeachesAndClassesDTO dto = new TeachesAndClassesDTO();
            dto.setClassIds(teaches.getClassIds());
            dto.setCourseId(teaches.getCourseId());
            dto.setTeacherId(teaches.getTeacherId());
            dto.setTeachId(teaches.getTeachId());
            ResultVO<String> resultVO = classesService.getClassNamesByIds(teaches.getClassIds());
            dto.setClassNames(resultVO.getResult());
            return ResultVO.success("教学安排详情获取成功", dto);
        } catch (Exception e) {
            return ResultVO.fail("获取教学安排详情时发生异常：" + e.getMessage());
        }
    }

    @Override
    public ResultVO<List<Teaches>> getTeachesList(Teaches teaches, int page, int size) {
        QueryWrapper<Teaches> queryWrapper = new QueryWrapper<>();

        // 课程id（模糊查询）
        if (teaches.getCourseId() != null &&!teaches.getCourseId().isEmpty()) {
            queryWrapper.like("course_id", teaches.getCourseId());
        }

        // 教师id（模糊查询）
        if (teaches.getTeacherId() != null &&!teaches.getTeacherId().isEmpty()) {
            queryWrapper.like("teacher_id", teaches.getTeacherId());
        }

        // 班级ids（模糊查询）
        if (teaches.getClassIds() != null &&!teaches.getClassIds().isEmpty()) {
            queryWrapper.like("class_ids", teaches.getClassIds());
        }

        // 分页查询（page从1开始，size为每页大小）
        Page<Teaches> pageResult = this.page(new Page<>(page, size), queryWrapper);

        List<Teaches> list = this.list(queryWrapper);
        int total= list.size();
        // 返回当前页数据列表
        return ResultVO.success("教学安排列表获取成功", pageResult.getRecords(),total);
    }

    @Override
    public ResultVO<Teaches> addTeaches(Teaches teaches) {
        try {
            // 检查教学安排id是否已存在（一般新增时id由数据库自增，这里主要检查业务关联的唯一性等，假设课程、教师、班级组合不能重复）
            QueryWrapper<Teaches> qw = new QueryWrapper<>();
            qw.eq("course_id", teaches.getCourseId())
                    .eq("teacher_id", teaches.getTeacherId())
                    .eq("class_ids", teaches.getClassIds());
            if (this.getOne(qw) != null) {
                return ResultVO.fail("该课程安排已存在");
            }

            boolean saveSuccess = this.save(teaches);
            if (!saveSuccess) {
                return ResultVO.fail("教学安排添加失败");
            }
            return ResultVO.success("教学安排添加成功", teaches);
        } catch (Exception e) {
            return ResultVO.fail("添加教学安排时发生异常：" + e.getMessage());
        }
    }

    @Override
    public ResultVO<Teaches> addTeaches2(String classNames, String courseName, String teacherId) {
        try {
            if(classNames==null || classNames.trim().isEmpty()){
                return ResultVO.fail("班级名称不能为空");
            }
            String[] classesArray = classNames.split("[、,| ，]");
            if(classesArray==null){
                return ResultVO.fail("班级名称不合规");
            }
            List<String> classIdList = new ArrayList<>();
            for(String className:classesArray){
                QueryWrapper<Classes>queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("class_name",className);
                Classes classes = classesService.getOne(queryWrapper);
                if(classes!=null){
                    classIdList.add(classes.getClassId());
                }
            }
            String classIds = String.join(",",classIdList);
            System.out.println(classIds);
            if(courseName==null || courseName.trim().isEmpty()) {
                return ResultVO.fail("课程名称不能为空");
            }
            ResultVO<String> resultVO1  = coursesService.getCourseIdByName(courseName);
            String courseId = resultVO1.getResult();
            if(teacherId==null || teacherId.trim().isEmpty()){
                return ResultVO.fail("教师id不能为空");
            }
            Teaches teaches = new Teaches();
            teaches.setClassIds(classIds);
            teaches.setCourseId(courseId);
            teaches.setTeacherId(teacherId);
            boolean saveSuccess = this.save(teaches);
            if (!saveSuccess) {
                return ResultVO.fail("教学安排添加失败");
            }
            return ResultVO.success("教学安排添加成功", teaches);
        } catch (Exception e) {
            return ResultVO.fail("添加教学安排时发生异常：" + e.getMessage());
        }
    }

    @Override
    public ResultVO<Teaches> updateTeaches(Teaches teaches) {
        try {
            // 检查教学安排是否存在
            Teaches existingTeaches = this.getOne(new QueryWrapper<Teaches>().eq("teach_id", teaches.getTeachId()));
            if (existingTeaches == null) {
                return ResultVO.fail("教学安排id不存在");
            }

            // 更新字段（只更新非空值且非空字符串）
            String courseId = teaches.getCourseId();
            if (courseId != null &&!courseId.trim().isEmpty()) {
                existingTeaches.setCourseId(courseId);
            }

            String teacherId = teaches.getTeacherId();
            if (teacherId != null &&!teacherId.trim().isEmpty()) {
                existingTeaches.setTeacherId(teacherId);
            }

            String classIds = teaches.getClassIds();
            if (classIds != null &&!classIds.trim().isEmpty()) {
                existingTeaches.setClassIds(classIds);
            }
            boolean updateSuccess = this.updateById(existingTeaches);
            if (!updateSuccess) {
                return ResultVO.fail("教学安排信息更新失败");
            }
            return ResultVO.success("教学安排信息更新成功", existingTeaches);
        } catch (Exception e) {
            return ResultVO.fail("更新教学安排时发生异常：" + e.getMessage());
        }
    }

    @Override
    public ResultVO<Teaches> deleteTeaches(Integer teachId) {
        try {
            // 检查教学安排是否存在
            Teaches existingTeaches = this.getOne(new QueryWrapper<Teaches>().eq("teach_id", teachId));
            if (existingTeaches == null) {
                return ResultVO.fail("教学安排id不存在");
            }

            //删除教学id也需要删除相关的作业信息
            List<Assignments> list = assignmentsService.list(new QueryWrapper<Assignments>().eq("teach_id",teachId));
            if(!list.isEmpty()||list!=null){
                for(Assignments assignments:list){
                    assignmentsService.deleteAssignment(assignments.getAssignmentId());
                }
            }
            boolean deleteSuccess = this.removeById(teachId);
            if (!deleteSuccess) {
                return ResultVO.fail("教学安排删除失败");
            }
            return ResultVO.success("教学安排删除成功");
        } catch (Exception e) {
            return ResultVO.fail("删除教学安排时发生异常：" + e.getMessage());
        }
    }

    @Override
    public ResultVO<List<CoursesAndTeachesAndClassesDTO>> getCourseTeachesInfoByTeacherId(String teacherId, String courseName, String courseCredits, int page, int size) {
        try {
            // 检查教师是否存在
            Teachers existingTeacher = teachersMapper.selectById(teacherId);
            if (existingTeacher == null) {
                return ResultVO.fail("教师工号不存在");
            }

            // 查询该教师的所有教学安排信息
            List<CoursesAndTeachesDTO> allList = teachesMapper.getInfoByTeacherId(teacherId,courseName,courseCredits);
            if (allList == null || allList.isEmpty()) {
                return ResultVO.fail("该教师未有教学安排");
            }

            //返回结果包装
            List<CoursesAndTeachesAndClassesDTO> list = new ArrayList<>();
            for (CoursesAndTeachesDTO dto:allList){
                CoursesAndTeachesAndClassesDTO dto1 = new CoursesAndTeachesAndClassesDTO();
                dto1.setClassIds(dto.getClassIds());
                dto1.setCourseCredits(dto.getCourseCredits());
                dto1.setCourseDescription(dto.getCourseDescription());
                dto1.setCourseId(dto.getCourseId());
                dto1.setCourseName(dto.getCourseName());
                dto1.setDepartment(dto.getDepartment());
                dto1.setTeacherId(dto.getTeacherId());
                dto1.setTeachId(dto.getTeachId());
                ResultVO<String> resultVO= classesService.getClassNamesByIds(dto.getClassIds());
                dto1.setClassNames(resultVO.getResult());
                list.add(dto1);
            }
            int total = list.size();
            // 计算分页起始和结束索引
            int startIndex = (page - 1) * size;
            int endIndex = Math.min(startIndex + size, total);
            // 截取当前页的数据
            List<CoursesAndTeachesAndClassesDTO> pageList = list.subList(startIndex, endIndex);
            return ResultVO.success("查询成功", pageList,total);
        } catch (Exception e) {
            return ResultVO.fail("查询教学安排时发生异常：" + e.getMessage());
        }
    }

    @Override
    public ResultVO<List<CoursesAndTeachesAndTeachersAndClasssesDTO>> getInfoByClassId(String classId, String teacherName, String courseName, String courseCredits, int page, int size) {
        try {
            // 参数校验
            if (classId==null || classId=="") {
                return ResultVO.fail("班级ID不能为空");
            }
            // 查询该教师的所有教学安排信息（带班级模糊查询）
            List<CoursesAndTeachesAndTeachersDTO> allList = teachesMapper.getInfoByClassId(classId,teacherName,courseName,courseCredits);

            if (allList == null || allList.isEmpty()) {
                return ResultVO.fail("未找到匹配的课程信息");
            }

            List<CoursesAndTeachesAndTeachersAndClasssesDTO> list = new ArrayList<>();
            for(CoursesAndTeachesAndTeachersDTO dto:allList){
                CoursesAndTeachesAndTeachersAndClasssesDTO dto1 = new CoursesAndTeachesAndTeachersAndClasssesDTO();
                dto1.setClassIds(dto.getClassIds());
                dto1.setCourseCredits(dto.getCourseCredits());
                dto1.setCourseDescription(dto.getCourseDescription());
                dto1.setCourseId(dto.getCourseId());
                dto1.setCourseName(dto.getCourseName());
                dto1.setDepartment(dto.getDepartment());
                dto1.setTeacherId(dto.getTeacherId());
                dto1.setTeacherName(dto.getTeacherName());
                dto1.setTeachId(dto.getTeachId());
                ResultVO<String> resultVO  = classesService.getClassNamesByIds(dto.getClassIds());
                dto1.setClassNames(resultVO.getResult());
                list.add(dto1);
            }
            int total = list.size();
            // 计算分页起始和结束索引
            int startIndex = (page - 1) * size;
            int endIndex = Math.min(startIndex + size, list.size());

            // 截取当前页的数据
            List<CoursesAndTeachesAndTeachersAndClasssesDTO> pageList = list.subList(startIndex, endIndex);
            return ResultVO.success("查询成功", pageList,total);
        } catch (Exception e) {
            return ResultVO.fail("查询课程信息失败：" + e.getMessage());
        }
    }

    @Override
    public ResultVO<List<String>> getClassNamesListByTeacherId(String teacherId) {
        QueryWrapper<Teaches> teachesQueryWrapper = new QueryWrapper<>();
        teachesQueryWrapper.eq("teacher_id",teacherId);
        List<Teaches> list = this.list(teachesQueryWrapper);
        if(list==null || list.isEmpty()){
            return ResultVO.fail("未有教学安排，无法获取班级");
        }
        List<String> list1 = new ArrayList<>();
        for(Teaches teaches:list){
            ResultVO<String> resultVO = classesService.getClassNamesByIds(teaches.getClassIds());
            list1.add(resultVO.getResult());
        }
        return ResultVO.success("查询成功",list1);
    }

}
